<?php
/** 状态的接口，定义不同状态下的行为 */
interface State
{
    public function open();
    public function close();
}
/** 上下文，管理状态对象并通过状态对象实现功能 */
class Context
{
    /** @var State $state 当前状态 */
    protected $state = null;
    public function __construct()
    {
        $this->state = new CloseState($this);
    }
    /** @param State $state */
    public function setState($state)
    {
        $this->state = $state;
    }
    public function open()
    {
        return $this->state->open();
    }
    public function close()
    {
        return $this->state->close();
    }
}

class OpenState implements State
{
    /** @var Context $context */
    protected $context;
    public function __construct($context)
    {
        $this->context = $context;
    }
    public function open()
    {
        echo "Error:已打开\r\n";
    }
    public function close()
    {
        echo "关闭\r\n";
        $this->context->setState(new CloseState($this->context));
    }
}
class CloseState implements State
{
    /** @var Context $context */
    protected $context;
    public function __construct($context)
    {
        $this->context = $context;
    }
    public function open()
    {
        echo "打开\r\n";
        $this->context->setState(new OpenState($this->context));
    }
    public function close()
    {
        echo "Error:已关闭\r\n";
    }
}

header('Content-Type: text/plain');

$context = new Context;
$context->open();
$context->open();
$context->close();
